package com.tbit.uqbike.webmanager.controller;

import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.common.enums.OperaPswEnum;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.constant.RedisKeyConstant;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.*;
import com.tbit.uqbike.object.pojo.dto.AfterSaleContactDTO;
import com.tbit.uqbike.object.pojo.dto.EditGiftCardExpireDateDTO;
import com.tbit.uqbike.object.pojo.dto.EditVipCardExpireDateDTO;
import com.tbit.uqbike.object.pojo.dto.UpdateBlackListDTO;
import com.tbit.uqbike.object.pojo.vo.AdvertConfigAdAccount;
import com.tbit.uqbike.object.pojo.vo.CouponCheckVO;
import com.tbit.uqbike.object.pojo.vo.UserGiftCardAreaVO;
import com.tbit.uqbike.object.pojo.vo.UserRefundLogVO;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.base.RedisService;
import com.tbit.uqbike.service.business.OperaPswService;
import com.tbit.uqbike.service.business.SupportService;
import com.tbit.uqbike.service.business.UserService;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import com.tbit.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 额外功能接口
 *
 * @Author:BUGTian
 * @DATE: 2022/6/10
 */
@RestController
@RequestMapping("/support")
public class SupportController {

    @Autowired
    private SupportService supportService;
    @Autowired
    private RedisService redisService;
    @Resource
    private UserService userService;
    @Autowired
    private OperaPswService operaPswService;

    private static final String TOKEN_SEPARATOR = ":";






    /**
     * 手动执行定时任务
     *
     * @param className  类名
     * @param methodName 方法名
     * @param sing       密钥
     * @return
     */
    @GetMapping("/executeTask")
    public Result executeTask(String className, String methodName, String sing) {
        if (StringUtils.isEmpty(className) || StringUtils.isEmpty(methodName)) {
            return Result.error("参数有误");
        }
        /**操作密码校验*/
        if (!OperaPswConstant.ADMIN_OPERA_PSW.equals(sing)) {
            throw new BaseException(SystemCodeEnum.OPERA_PAW_ERROR);
        }
        return supportService.executeTask(className, methodName);
    }

    /**
     * 获取用户修改礼品卡金额推荐区域
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("/getRecommendArea")
    public Result<List<UserGiftCardAreaVO>> getUserGiftCardRecommendArea(@NotNull Integer userId) {
        List<UserGiftCardAreaVO> list = supportService.getUserGiftCardRecommendArea(userId);
        return Result.success(list);
    }


    /**
     * 删除用户登录缓存
     *
     * @param userId 用户id
     * @param sing   操作密码
     * @return
     */
    @DeleteMapping("/deleteRedisLoginCache")
    public Result deleteRedisLoginCache(@NotNull Integer userId, String sing) {
        /**操作密码校验*/
        operaPswService.checkOperaPsw(BaseController.getLogin(ServletUtils.getRequest()),
                    OperaPswEnum.OPERA_PSW_OPERATION_CONFIG.getModule(), sing);

        User user =userService.getByUserId(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        String redisKey = new StringBuilder(RedisKeyConstant.CLIENT_LOGIN_USER_KEY)
                .append(TOKEN_SEPARATOR)
                .append(user.getAccountId())
                .append(TOKEN_SEPARATOR)
                .append(user.getUserId())
                .toString();
        String tokenValidKey = redisService.get(redisKey);
        if (StringUtils.isNotEmpty(tokenValidKey)) {
            redisService.del(tokenValidKey);
        }
        redisService.del(redisKey);
        return Result.success();
    }


    /**
     * 根据品牌id查询旗下所有加盟商和区域账号
     *
     * @param brandId 品牌id
     * @return
     */
    @GetMapping("/queryAccountUserByBrandId")
    public Result<List<AccountUser>> queryAccountUserByBrandId(Integer brandId) {
        return supportService.queryAccountUserByBrandId(brandId);
    }


    /**
     * 会员卡置为失效
     *
     * @param editVipCardExpireDateDTO
     * @return
     */
    @PutMapping("/editVipCardExpireDate")
    @OperateLog(module = ModuleEnum.VIPCARD, methods = MethodEnum.VIPCARD_CANCAL)
    public Result editVipCardExpireDate(@RequestBody EditVipCardExpireDateDTO editVipCardExpireDateDTO) {
        /**操作密码校验*/
        operaPswService.checkOperaPsw(BaseController.getLogin(ServletUtils.getRequest()),
                    OperaPswEnum.OPERA_PSW_COUPONS_CONFIG.getModule(), editVipCardExpireDateDTO.getSing());

        return supportService.editVipCardExpireDate(editVipCardExpireDateDTO.getOrderNO(), editVipCardExpireDateDTO.getOldExpireDate(), editVipCardExpireDateDTO.getNewExpireDate());
    }

    /**
     * 删除优惠券前检查
     *
     * @param couponId 优惠券id
     * @return
     */
    @GetMapping("/deleteCouponCheck")
    public Result<CouponCheckVO> deleteCouponCheck(Integer couponId) {
        CouponCheckVO couponCheck = supportService.deleteCouponCheck(couponId);
        return Result.success(couponCheck);
    }

    /**
     * 根据商户订单号查询退款日志
     *
     * @param orderNO 备注里的商户订单号
     * @return
     */
    @GetMapping("/queryUserRefundLogByOrderNO")
    public Result<List<UserRefundLogVO>> queryUserRefundLogByOrderNO(String orderNO) {
        //根据商户订单号查询退款日志
        List<UserRefundLogVO> userRefundLogVOList = supportService.queryUserRefundLogByOrderNO(orderNO);
        return Result.success(userRefundLogVOList);
    }

    /**
     * 平台服务费催缴配置
     *
     * @param rushPayFeeConfig
     * @param accountId        品牌id
     * @return
     */
    @PostMapping("/editRushPayFeeConfig")
    @OperateLog(module = ModuleEnum.RUSHPAYFEECONFIG, methods = MethodEnum.RUSHPAYFEECONFIG_EDIT)
    public Result editRushPayFeeConfig(@RequestBody RushPayFeeConfig rushPayFeeConfig, Integer accountId) {
        if (accountId == null) {
            return Result.error("品牌id不能为空");
        }
        return supportService.editRushPayFeeConfig(rushPayFeeConfig, accountId);
    }

    /**
     * 查询平台服务费催缴配置
     *
     * @param accountId 品牌id
     * @return
     */
    @GetMapping("/queryRushPayFeeConfig")
    public Result<RushPayFeeConfig> queryRushPayFeeConfig(Integer accountId) {
        if (accountId == null) {
            return Result.error("品牌id不能为空");
        }
        return Result.success(supportService.queryRushPayFeeConfig(accountId));
    }


    /**
     * 礼品卡置为失效
     *
     * @param editGiftCardExpireDateDTO
     * @return
     */
    @OperateLog(module = ModuleEnum.GIFTCARD, methods = MethodEnum.GIFTCARD_EDIT)
    @PutMapping("/editGiftCardExpireDate")
    public Result editGiftCardExpireDate(@RequestBody EditGiftCardExpireDateDTO editGiftCardExpireDateDTO) {
        return supportService.editGiftCardExpireDate(editGiftCardExpireDateDTO);
    }

    /**
     * 举报管理，清洁上报，摆车上报，巡检上报 驳回
     *
     * @param logId 日志主键id
     * @param type  举报管理:1，清洁上报:2，摆车上报:3，巡检上报:4
     * @return
     */
    @PutMapping("/rejectControl")
    @OperateLog(module = ModuleEnum.OPERATIONS_MANAGEMENT, methods = MethodEnum.OPERATIONS_MANAGEMENT_EDIT_STATUS)
    public Result rejectControl(@NotNull Integer logId, @NotNull Integer type) {
        return supportService.rejectControl(logId, type);
    }


    /**
     * 查询附近站点未审核信息
     *
     * @param adAccountId 区域id
     * @param lat         纬度
     * @param lon         经度
     * @param distance    距离 (单位:米)
     * @param mapType     地图类型
     * @return
     */
    @GetMapping("/queryNearByParkPointApply")
    public Result<List<ParkPointApply>> queryNearByParkPointApply(@NotNull Integer adAccountId, @NotNull Double lat, @NotNull Double lon, @NotNull Integer distance, Integer mapType) {
        if (adAccountId == null || lat == null || lon == null || distance == null) {
            return Result.error("参数有误");
        }
        List<ParkPointApply> list = supportService.queryNearByParkPointApply(adAccountId, lat, lon, distance, mapType);
        return Result.success(list);
    }

    /**
     * 批量修改站点容量和误差范围
     *
     * @param file        站点导出的excel文件
     * @param adAccountId 区域id
     * @return
     */
    @PostMapping("/batchUpdateParkPointAllowRangeAndCapacity")
    public Result batchUpdateParkPointAllowRangeAndCapacity(@RequestParam("file") MultipartFile file, @NotNull Integer adAccountId, @RequestParam(defaultValue = "0") Integer mapType) {
        return supportService.batchUpdateParkPointAllowRangeAndCapacity(file, adAccountId, mapType);
    }

    /**
     * 批量开启站点功能
     *
     * @param file      文件
     * @param accountId 运营区域id
     * @return 。
     */
    @PostMapping("/batchUpdateParkFeature")
    public Result batchUpdateParkPoint(@RequestParam("file") MultipartFile file, @NotNull Integer accountId) {
        return supportService.batchUpdateParkFeature(file, accountId);
    }

    /**
     * 获取批量修改站点模板
     *
     * @param adAccountId 区域id
     * @param type        0:空模板，1：带站点数据
     * @return
     */
    @GetMapping("/getBatchUpdateParkPointTemplate")
    public Result getBatchUpdateParkPointTemplate(@NotNull Integer adAccountId, @NotNull Integer type, @RequestParam(defaultValue = "0") Integer mapType) {
        return supportService.getBatchUpdateParkPointTemplate(adAccountId, type, mapType);
    }

    /**
     * 获取批量修改站点功能模板
     *
     * @param accountId 运营区域id
     * @param type      0-空模板  1-有数据
     * @return 。
     */
    @GetMapping("/getBatchUpdateParkFeatureTemplate")
    public Result getBatchUpdateParkFeatureTemplate(@NotNull Integer accountId, @NotNull Integer type) {
        return supportService.getBatchUpdateParkFeatureTemplate(accountId, type);
    }

    /**
     * 根据品牌id查询品牌下配置了区域广告配置的区域
     *
     * @param accountId 品牌id
     * @return
     */
    @GetMapping("/queryAdvertConfigAdAccount")
    public Result<List<AdvertConfigAdAccount>> queryAdvertConfigAdAccount(@NotNull Integer accountId) {
        List<AdvertConfigAdAccount> list = supportService.queryAdvertConfigAdAccount(accountId);
        return Result.success(list);
    }

    /**
     * 删除广告配置
     *
     * @param accountId 区域或者品牌id都行
     * @return
     */
    @DeleteMapping("/deleteAdvertConfig")
    public Result deleteAdvertConfig(@NotNull Integer accountId) {
        supportService.deleteAdvertConfig(accountId);
        return Result.success();
    }

    /**
     * 修改售后联系方式
     *
     * @param afterSaleContactDTO
     * @return
     */
    @PostMapping("/editAfterSaleContact")
    public Result editAfterSaleContact(@RequestBody AfterSaleContactDTO afterSaleContactDTO) {
        return supportService.editAfterSaleContact(afterSaleContactDTO);
    }

    /**
     * 获取售后联系方式
     *
     * @param accountId
     * @return
     */
    @GetMapping("/getAfterSaleContact")
    public Result<List<AfterSaleContact>> getAfterSaleContact(@NotNull Integer accountId) {
        return supportService.getAfterSaleContact(accountId);
    }


    /**
     * 更新用户黑名单
     *
     * @param updateBlackListDTO
     * @return
     */
    @PutMapping("/updateUserBlackList")
    public Result updateUserBlackList(@RequestBody UpdateBlackListDTO updateBlackListDTO) {
        //更新用户黑名单
        Assert.notNulls("缺少必要参数", updateBlackListDTO.getAddTime(), updateBlackListDTO.getExpireTime(), updateBlackListDTO.getAccountId());
        if (StringUtils.isEmpty(updateBlackListDTO.getPhone()) && StringUtils.isEmpty(updateBlackListDTO.getIdNO())) {
            return Result.error("参数有误");
        }
        return supportService.updateUserBlackList(updateBlackListDTO);
    }

    /**
     * 查询品牌虚拟充值功能配置
     *
     * @param brandId
     * @return
     */
    @GetMapping("/queryVirtualRechargeFunction")
    public Result<VirtualRechargeFunction> queryVirtualRechargeFunction(Integer brandId) {
        if (brandId == null) {
            return Result.error("品牌id不能为空");
        }
        VirtualRechargeFunction virtualRechargeFunction = supportService.queryVirtualRechargeFunction(brandId);
        return Result.success(virtualRechargeFunction);
    }

    /**
     * 修改品牌虚拟充值功能配置
     *
     * @param virtualRechargeFunction
     * @return
     */
    @PutMapping("/updateVirtualRechargeFunction")
    public Result updateVirtualRechargeFunction(@RequestBody VirtualRechargeFunction virtualRechargeFunction) {
        if (virtualRechargeFunction.getBrandId() == null || virtualRechargeFunction.getFlag() == null) {
            return Result.error("参数有误");
        }
        supportService.updateVirtualRechargeFunction(virtualRechargeFunction);
        return Result.success();
    }

    /**
     * 根据手机号批量操作模板
     *
     * @return
     */
    @GetMapping("/getBatchByPhoneTemplate")
    public Result<Object> getBatchAddTemplate() {
        ExcelUtil<BatchByPhone> excelUtil = new ExcelUtil<>(BatchByPhone.class);
        List<BatchByPhone> list = new ArrayList<>();
        BatchByPhone batchByPhone1 = new BatchByPhone();
        batchByPhone1.setPhone("18207115364");
        list.add(batchByPhone1);
        BatchByPhone batchByPhone2 = new BatchByPhone();
        batchByPhone2.setPhone("18207110000");
        list.add(batchByPhone2);
        return Result.success(excelUtil.exportExcel(list, "根据手机号批量操作模板").getData());
    }
}
